<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>原生js实现事件委托</title>
</head>
<body>
  <h1>原生JS实现事件委托</h1>
  <h2>什么是事件委托？</h2>
  <h3>事件委托就是利用事件冒泡，只指定一个事件处理程序，就可以管理某一类的所有事件。</h3>
  <div id="div">
    <ul id="ul">
      <li>0</li>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
    </ul>
    <button id="btn">添加一个li</button>
  </div>
  
</body>
<script>
  // 事件委托
  let ul = document.getElementById('ul')
      ul.onclick = function(event) {
        console.log(event);
        event = event || window.event
        let target = event.target
        if (target.nodeName == 'LI') {
          // 委托的事情
          alert(target.innerHTML)
        }
      }

  let btn = document.getElementById('btn')
      btn.onclick = function() {
        let li = document.createElement('li')
        li.textContent = ul.children.length
        ul.appendChild(li)
      }    
</script>
</html>